<template>
  <div>
    <div class="mb-4">
      <el-button type="primary" @click="openForm('create')">
        <Icon icon="ep:plus" />
        添加数据表
      </el-button>
    </div>
    <el-table v-loading="loading" :data="list" @row-click="handleRowClick">
      <el-table-column label="表名称" align="center" prop="name" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" @click.stop="openForm('update', scope.row.id)">
            修改
          </el-button>
          <el-button link type="danger" @click.stop="handleDelete(scope.row.id)"> 删除 </el-button>
          <el-button link type="success" @click.stop="handleViewFields(scope.row)">
            查看字段
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ProjectCellTableApi, ProjectCellTableVO } from '@/api/agent/table'

defineOptions({ name: 'DataTableTab' })

const props = defineProps<{
  projectId: number
  cellId: number | null
}>()

const emit = defineEmits(['open-form', 'view-fields'])

const loading = ref(true)
const list = ref<ProjectCellTableVO[]>([])

const getList = async () => {
  if (!props.cellId) {
    list.value = []
    return
  }
  loading.value = true
  try {
    const res = await ProjectCellTableApi.getProjectCellTableList({
      cellId: props.cellId
    })
    list.value = res
  } finally {
    loading.value = false
  }
}

const openForm = (type: string, id?: number) => {
  emit('open-form', type, id, props.cellId)
}

const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('是否确认删除该数据表？')
    await ProjectCellTableApi.deleteProjectCellTable(id)
    ElMessage.success('删除成功')
    await getList()
  } catch (e) {
    /* empty */
  }
}

const handleRowClick = (row: ProjectCellTableVO) => {
  handleViewFields(row)
}

const handleViewFields = (row: ProjectCellTableVO) => {
  emit('view-fields', row)
}

watch(
  () => props.cellId,
  (newVal) => {
    if (newVal) {
      getList()
    } else {
      list.value = []
    }
  },
  { immediate: true }
)

defineExpose({ getList })
</script>